package com.chongyahhh.security.security.handler;

import com.alibaba.fastjson.JSONObject;
import com.chongyahhh.security.bean.model.BaseResult;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author chongyahhh
 * 对匿名用户无权限的处理
 */
@Component
public class JsonAuthenticationEntryPoint implements AuthenticationEntryPoint {

    // spring security 匿名用户访问无权限信息被认定为无认证，所以这里要做个判断
    private final String NEED_LOGIN_PREFIX = "Full authentication is required";

    private final String NEED_LOGIN = "请先登录";

    @Override
    public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        String message = e.getMessage();
        if(message.contains(NEED_LOGIN_PREFIX)){
            message = NEED_LOGIN;
        }
        httpServletResponse.setCharacterEncoding("utf-8");
        httpServletResponse.setContentType("application/json;charset=utf-8");
        httpServletResponse.getWriter().print(JSONObject.toJSONString(new BaseResult<String>(message, false, null)));
    }
}
